var jcrop_api, boundx, boundy;

function updateImg(path, newWidth, newHeight) {

    $("#url").val(path);
    $("#target").attr("src", "../" + path);
    $("#preview").attr("src", "../" + path);
    $("#preview1").attr("src", "../" + path);
    $("#preview2").attr("src", "../" + path);

    $('#target').Jcrop({
        sideHandles:false,
        allowSelect:false,
        onChange: updatePreview,
        onSelect: updatePreview,
        aspectRatio: 1
    }, function() {
        var bounds = this.getBounds();
        boundx = bounds[0];
        boundy = bounds[1];
        jcrop_api = this;
        var point = 0;
        if(newWidth > newHeight){
            point = (parseInt(400) - parseInt(newHeight))/2;
            jcrop_api.setOptions({setSelect:[point, 0, 400, 400]});            
        }else{
            point = (parseInt(400) - parseInt(newWidth))/2;
            jcrop_api.setOptions({setSelect:[0, point, 400, 400]});
        }
    });
}

function updatePreview(c) {

    if (parseInt(c.w) > 0){
        var rx = 50 / c.w;
        var ry = 50 / c.h;

        $("#imgX").val(c.x);
        $("#imgY").val(c.y);
        $("#imgWidth").val(c.w);
        $("#imgHeight").val(c.h);
        $('#preview').css({
            width: Math.round(rx * boundx) + 'px',
            height: Math.round(ry * boundy) + 'px',
            marginLeft: '-' + Math.round(rx * c.x) + 'px',
            marginTop: '-' + Math.round(ry * c.y) + 'px'
        });

        var rx1 = 100 / c.w;
        var ry1 = 100 / c.h;
        $('#preview1').css({
            width: Math.round(rx1 * boundx) + 'px',
            height: Math.round(ry1 * boundy) + 'px',
            marginLeft: '-' + Math.round(rx1 * c.x) + 'px',
            marginTop: '-' + Math.round(ry1 * c.y) + 'px'
        });

        var rx2 = 200 / c.w;
        var ry2 = 200 / c.h;
        $('#preview2').css({
            width: Math.round(rx2 * boundx) + 'px',
            height: Math.round(ry2 * boundy) + 'px',
            marginLeft: '-' + Math.round(rx2 * c.x) + 'px',
            marginTop: '-' + Math.round(ry2 * c.y) + 'px'
        });
    }
}